<?php

declare(strict_types=1);

namespace app\command;

use app\common\config\model\ConfigHall;
use app\common\config\model\ConfigSource;
use app\common\config\model\ConfigStore;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerContact;
use app\common\customer\model\CustomerInvite;
use app\common\customer\model\CustomerMami;
use app\common\order\model\Order;
use app\common\order\model\OrderBom;
use app\common\order\model\OrderVip;
use app\common\system\model\User;
use PDO;
use PDOException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Sync extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync')
            ->addOption('type', null, Option::VALUE_REQUIRED, 'sync type')
            ->setDescription('the sync command');
    }

    protected function execute(Input $input, Output $output)
    {
        $type = $input->getOption('type');
        switch ($type) {
            case 'order':
                $this->syncOrder($input, $output);
                break;
            default:
                break;
        }
    }

    private function syncOrder($input, $output)
    {
        print_r("sync order start... \n");
        // 指令输出
        // 读取./data/1.xlsx文件
        $file = 'data/0926.xlsx';
        if (!file_exists($file)) {
            $output->writeln('file not exists\n');
            return;
        } else {
            $output->writeln('file exists\n');
        }

        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($file);
        // 获取工作表
        $sheets = $spreadsheet->getSheetNames();


        $spreadsheet->setActiveSheetIndex(0);
        $sheet = $spreadsheet->getActiveSheet();
        $highestRow = $sheet->getHighestRow(); // 取得总行数

        // $highestRow = 17126;


        $orderModel = new Order();
        $storeModel = new ConfigStore();
        $sourceModel = new ConfigSource();
        print_r("start loop...");

        // 分页处理 每页100条
        $pageSize = 100;
        $pages = ceil($highestRow / $pageSize);
        // 分页处理
        for ($i = 1; $i <= $pages; $i++) {
            $start = ($i - 1) * $pageSize + 2;
            $end = $i * $pageSize + 1;
            $end = $end > $highestRow ? $highestRow : $end;

            // 逐行处理
            for ($row = $start; $row <= $end; $row++) {
                $customerModel = new Customer();
                $contactModel = new CustomerContact();

                // A 创建时间 获取日期格式
                $createTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($sheet->getCell('A' . $row)->getValue());
                $createTime = $createTime->format('Y-m-d H:i:s');
                $createTime = strtotime($createTime);

                // B 渠道
                $sourceText = $sheet->getCell('B' . $row)->getValue();
                $source = $sourceModel->where('title', 'like', '%' . $sourceText . '%')->find();
                // C 姓名
                $fullName = $sheet->getCell('C' . $row)->getValue();
                $fullName = $fullName ? $fullName : '';

                // D 联系方式
                $contact = $sheet->getCell('D' . $row)->getValue();

                // I 预约门店
                $storeText = $sheet->getCell('I' . $row)->getValue();
                $store = $storeModel->where('title', 'like', '%' . $storeText . '%')->find();

                // F 是否有效
                $isValid = $sheet->getCell('F' . $row)->getValue();

                // E 预产期 event_date
                $eventDate = $sheet->getCell('E' . $row)->getValue();
                if (is_int($eventDate)) {
                    $eventDate = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($sheet->getCell('E' . $row)->getValue());
                    $eventDate = $eventDate->format('Y-m-d H:i:s');
                }

                // O 详情1 remark
                $remark = $sheet->getCell('O' . $row)->getValue();

                $customerData = [];
                $customerData['fullname'] = $fullName;
                $status = $isValid == '是' ? 5 : 6;
                $customerData['status'] = $status;
                $customerData['source_id'] = $source ? $source->id : 0;
                $customerData['create_id'] = 1;
                $customerData['operator_id'] = 1;
                $customerData['create_time'] = $createTime;

                // 开启事务
                $customerModel->startTrans();
                try {
                    $customerModel->save($customerData);
                } catch (\Exception $e) {
                    $customerModel->rollback();
                    $output->writeln('customer save error');
                    print_r($e->getMessage());
                    continue;
                }

                $memberId = $customerModel->id;
                // 保存联系方式
                $contactData = $this->formatContact($contact);
                $contactData = array_map(function ($item) use ($memberId, $createTime) {
                    $item['operator_id'] = 1;
                    $item['member_id'] = $memberId;
                    $item['create_time'] = $createTime;
                    $item['role'] = 1;
                    return $item;
                }, $contactData);

                // 逐行保存
                $contactErrors = 0;
                foreach ($contactData as $contactItem) {
                    // 查找是否存在该客资
                    $contactExist = $contactModel->where('contact', $contactItem['contact'])->find();
                    if ($contactExist) {
                        $contactErrors++;
                        continue;
                    }

                    try {
                        $contactModel->save($contactItem);
                    } catch (\Exception $e) {
                        $contactErrors++;
                        print_r($e->getMessage());
                        continue;
                    }
                }

                if ($contactErrors >= count($contactData)) {
                    $customerModel->rollback();
                    $output->writeln('contact save error');
                    continue;
                }

                // 保存客资详情
                $modelMami = new CustomerMami();
                $mamiData = [];
                $mamiData['member_id'] = $memberId;
                $mamiData['store_id'] = $store ? $store->id : 0;
                $mamiData['event_date'] = $eventDate ? $eventDate : '';
                $mamiData['remark'] = $remark;
                $mamiData['create_id'] = 1;
                $mamiData['create_time'] = $createTime;
                try {
                    $modelMami->save($mamiData);
                } catch (\Exception $e) {
                    $customerModel->rollback();
                    $output->writeln('mami save error');
                    print_r($e->getMessage());
                    continue;
                }

                // H 跟进人
                $followUser = $sheet->getCell('H' . $row)->getValue();
                if ($followUser) {
                    $followUserModel = new User();
                    $followUserData = $followUserModel->where('realname', 'like', '%' . $followUser . '%')->find();
                    if ($followUserData) {
                        $followUserId = $followUserData->id;
                    } else {
                        $followUserId = 15;
                    }
                } else {
                    $followUserId = 15;
                }
                $customerAllocateModel = new CustomerAllocate();
                $allocateData = [];
                $allocateData['member_id'] = $memberId;
                $allocateData['create_id'] = $followUserId;
                $allocateData['from_user_id'] = $followUserId;
                $allocateData['user_id'] = $followUserId;
                $allocateData['create_time'] = $createTime;
                $allocateData['status'] = $status;
                try {
                    $customerAllocateModel->save($allocateData);
                } catch (\Exception $e) {
                    $customerModel->rollback();
                    $output->writeln('allocate save error');
                    print_r($e->getMessage());
                }


                // G 是否预约
                $isAppoint = $sheet->getCell('G' . $row)->getValue();

                if ($isAppoint == '是') {
                    // J 预约日期，日期格式
                    $appointTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($sheet->getCell('J' . $row)->getValue());
                    $appointTime = $appointTime->format('Y-m-d H:i:s');

                    // K 是否进店
                    $isStore = $sheet->getCell('K' . $row)->getValue();
                    // '' 1=已到点; 2=取消；3=改约
                    if ($isStore == '已到店') {
                        $inviteStatus = 1;
                    } else if ($isStore == '取消') {
                        $inviteStatus = 2;
                    } else if ($isStore == '改约') {
                        $inviteStatus = 3;
                    }

                    $modelInvite = new CustomerInvite();
                    $inviteData = [];
                    $inviteData['member_id'] = $memberId;
                    $inviteData['store_id'] = $store ? $store->id : 0;
                    $inviteData['invite_time'] = $appointTime;
                    $inviteData['status'] = $inviteStatus ? $inviteStatus : 0;
                    $inviteData['user_id'] = $followUserId;
                    $inviteData['create_time'] = $createTime;

                    try {
                        $modelInvite->save($inviteData);
                    } catch (\Exception $e) {
                        $customerModel->rollback();
                        $output->writeln('invite save error');
                        print_r($e->getMessage());
                    }
                }
                $customerModel->commit();

                // L 预约项目
                // $appointProject = $sheet->getCell('L' . $row)->getValue();

                // N 出单金额
                $totals = $sheet->getCell('N' . $row)->getValue();
                // P 详情2（客资情况）
                $detail2 = $sheet->getCell('P' . $row)->getValue();
                // Q 详情3 门店标记无效
                $detail3 = $sheet->getCell('Q' . $row)->getValue();
                // R 详情4
                $detail4 = $sheet->getCell('R' . $row)->getValue();
                // S 详情5
                $detail5 = $sheet->getCell('S' . $row)->getValue();

                if ($totals > 0) {
                    // M 出单日
                    $signDate = $sheet->getCell('M' . $row)->getValue();
                    if (is_int($signDate)) {
                        $signDate = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($sheet->getCell('M' . $row)->getValue());
                        $signDate = $signDate->format('Y-m-d H:i:s');
                    }
                    // 提交订单
                    $orderData = [];
                    $orderNo = date('YmdHis') . rand(1000, 9999);
                    $orderData['order_no'] = $orderNo;
                    $orderData['member_id'] = $memberId;
                    $orderData['source_id'] = $source ? $source->id : 0;
                    $orderData['user_id'] = $followUserId;
                    // $orderData['create_time'] = $signDate;
                    $orderData['totals'] = $totals;
                    $orderModel = new Order();
                    // 开启事务
                    $orderModel->startTrans();
                    try {
                        $orderModel->save($orderData);
                    } catch (\Exception $e) {
                        $orderModel->rollback();
                        $output->writeln('order save error');
                        print_r($e->getMessage());
                        continue;
                    }

                    // 提交订单详情
                    $orderVipModel = new OrderVip();
                    $orderVipData = [];
                    $orderVipData['user_id'] = $followUserId;
                    $orderVipData['order_no'] = $orderNo;
                    $orderVipData['order_id'] = $orderModel->id;
                    $orderVipData['name'] = $fullName;
                    $orderVipData['phone'] = $contactData[0]['contact'];
                    // 保存订单详情
                    try {
                        $orderVipModel->save($orderVipData);
                    } catch (\Exception $e) {
                        $orderModel->rollback();
                        $output->writeln('order vip save error');
                        print_r($e->getMessage());
                        continue;
                    }

                    // 更新客资状态
                    $orderBomModel = new OrderBom();
                    $orderBomData = [];
                    $orderBomData['member_id'] = $memberId;
                    $orderBomData['user_id'] = $followUserId;
                    $orderBomData['order_id'] = $orderModel->id;
                    $orderBomData['order_no'] = $orderNo;
                    // $orderBomData['create_time'] = st;

                    $eventDate = $sheet->getCell('E' . $row)->getValue();
                    if (is_int($eventDate)) {
                        $eventDate = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($sheet->getCell('E' . $row)->getValue());
                        $eventDate = $eventDate->format('Y-m-d H:i:s');
                    } else {
                        $eventDate = '';
                    }
                    $orderBomData['event_date'] = $eventDate;


                    $orderBomData['sign_date'] = $signDate;
                    $orderBomData['store_id'] = $store ? $store->id : 0;
                    $orderBomData['totals'] = $totals;
                    // 提交
                    try {
                        $orderBomModel->save($orderBomData);
                    } catch (\Exception $e) {
                        $orderModel->rollback();
                        // $customerModel->rollback();
                        $output->writeln('order bom save error');
                        print_r($e->getMessage());
                        continue;
                    }
                    $orderModel->commit();
                }

                $output->writeln('row: ' . $row . "\n");
            }
        }
    }

    private function formatContact($contact)
    {
        // 转为字符串
        $contact = strval($contact);
        $contact = trim($contact);

        // 是否存在 ”/“
        if (strpos($contact, '/')) {
            $contactArr = explode('/', $contact);
            // 每一项做trim
            $contactArr = array_map('trim', $contactArr);

            // 给每一项加上标签
            $contactArr = array_map(function ($item) {
                // 判断是否是手机号
                if (preg_match("/^1[3456789]\d{9}$/", $item)) {
                    return [
                        'type' => 1,
                        'contact' => $item
                    ];
                } else {
                    return [
                        'type' => 2,
                        'contact' => $item
                    ];
                }
            }, $contactArr);
        } else {
            // 判断是否是手机号
            if (preg_match("/^1[3456789]\d{9}$/", $contact)) {
                $contactArr = [
                    [
                        'type' => 1,
                        'contact' => $contact
                    ]
                ];
            } else {
                // 检测是否是两个在一起的手机号
                if (preg_match("/^1[3456789]\d{9}1[3456789]\d{9}$/", $contact)) {
                    $contactArr = [
                        [
                            'type' => 1,
                            'contact' => substr($contact, 0, 11)
                        ],
                        [
                            'type' => 1,
                            'contact' => substr($contact, 11, 11)
                        ]
                    ];
                } else {
                    $contactArr = [
                        [
                            'type' => 2,
                            'contact' => $contact
                        ]
                    ];
                }
            }
        }

        return $contactArr;
    }
}
